/*
 * PedalController.c
 *
 * Created: 24.09.2012 16:53:01
 *  Author: Sebastian Steppeler
 */
// author: Sebastian Steppeler copyright 2012
/*license: This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.*/

#include <avr/io.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <util/delay.h>
#include <util/twi.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include "typedefs.h"
#include "main.h"
#include "timer.h"
#include "Midi.h"
#include "ADC.h"
#include "eeprom.h"
#include "Pedal.h"

extern volatile char bNewSample;
extern volatile int iSampleExchange[8];
extern int iCurrentSample[8];
extern int iLastSample[8];
extern PEDAL Pedals[3];
extern volatile int8_t cPolarity;

extern volatile bool bBoot;
extern volatile char cCalibration;

int main(void)
{
	int8_t cPolTemp;
	int16_t iMin;
	int16_t iMax;
	
	if(!EELoadSettings())
		LoadStandardConfig();
	
	// make a copy of the eeprom setting of polarity:
	cPolTemp = cPolarity;
	cPolarity = 1;
	
	// init everything
	InitMidi();
	ADC_Init();
	bNewSample = false;
	ADC_StartConversion(0);
	RecalcPedalFactors();
	
	sei();
	
	_delay_ms(1500);
	
	// enter calibration mode if scheduled:
	if(cCalibration==CALIB_RUN)
	{		
		bNewSample = false;
		while(!bNewSample);
		FetchSample();
		iMin = iCurrentSample[0];
		iMax = iMin;
	}
			
	while(cCalibration==CALIB_RUN)
	{
		while(!bNewSample);
		FetchSample();
		
		if((cPolarity==1) && (iCurrentSample[0] < iMin-POLARITY_CHANGE_THRESHOLD))
		{
			iMin = 1023 - iMin;
			iMax = iMin;
			cPolarity = -1;
		}
		else if(iCurrentSample[0]>iMax)
			iMax = iCurrentSample[0];
	}
	
	if(cCalibration==CALIB_SAVE)
	{
		Pedals[0].iMin = iMin;
		Pedals[0].iMax = iMax;
		RecalcPedalFactors();
		EESaveSettings();
	}	
	else
		cPolarity = cPolTemp; // restore polarity setting
		
	// fetch actual new sample with changed polarity:
	bNewSample = false;
	while(!bNewSample);
		FetchSample();
			
    while(1) // main loop
    {
        CalcPedals();
    }
	
	return 1;
}